//
//  CustomTableView.m
//  QoilPublic
//
//  Created by SunChao on 17/9/13.
//  Copyright © 2017年 杨凯. All rights reserved.
//

#import "CustomTableView.h"
#import "OrderStatusCell.h"
#import "EvaluationCell.h"
#import "EvaluationedCell.h"
#import "SheetView.h"
#import "SheetView1.h"
@interface CustomTableView()<UITableViewDelegate,UITableViewDataSource>
{
    NSMutableArray *_evalArr;
}
@property (nonatomic,assign)BOOL isShow;
@property (nonatomic,assign)BOOL isPingJia;
@property (nonatomic,strong)SheetView *sheetView;
@property (nonatomic,copy)NSString *address;
@property (nonatomic,copy)NSString *orderId;
@property (nonatomic,strong)NSArray *timeArr;
@property (nonatomic,strong)NSArray *statusArr;
@property (nonatomic,copy)NSString *purId;
@property (nonatomic,copy)NSString *integral;
@end

@implementation CustomTableView

- (instancetype)initWithFrame:(CGRect)frame orderId:(NSString *)orderId orderAddress:(NSString *)address statusTime:(NSString *)statusTime stateText:(NSString *)stateText purId:(NSString *)purId integral:(NSString *)integral{
    self = [super initWithFrame:frame];
    if (self) {
        //tableView的代理
        self.delegate = self;
        self.dataSource = self;
        self.backgroundColor = [UIColor groupTableViewBackgroundColor];
        self.bounces = NO;
    }
    
    _address = address;
    _orderId = orderId;
    _integral = integral;
    _timeArr = [statusTime componentsSeparatedByString:@"," ];
    
    _statusArr = [stateText componentsSeparatedByString:@","];
    
    for (NSString *status in _statusArr) {
        if ([status isEqualToString:@"付款"]) {
            _isShow = YES;
        }
        if ([status isEqualToString:@"评价"]) {
            _isShow = YES;
            _isPingJia = YES;
            _integral = @"";
        }
    }
    _purId = purId;
    
    [self registerNib:[UINib nibWithNibName:@"OrderStatusCell" bundle:nil] forCellReuseIdentifier:@"OrderStatusCell"];
     [self registerNib:[UINib nibWithNibName:@"EvaluationCell" bundle:nil] forCellReuseIdentifier:@"EvaluationCell"];
     [self registerNib:[UINib nibWithNibName:@"EvaluationedCell" bundle:nil] forCellReuseIdentifier:@"EvaluationedCell"];
    
   
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(CommentSuccessAction) name:kNotificationCommentSuccess object:nil];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(ShowUserEvaluate:) name:@"ShowUserEvaluateNotification" object:nil];
    return self;
}
-(void)dealloc{
    
     [[NSNotificationCenter defaultCenter] removeObserver:self];
}
- (void)ShowUserEvaluate:(NSNotification *)notification{
    
    
    
}
- (void)CommentSuccessAction{

    [_sheetView disMissView];
    UIViewController *vc = [QViewUtility getCurrentVC];
    [vc.navigationController popViewControllerAnimated:YES];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (_isShow ==YES &&_isPingJia == NO) {
        return 2;
    }
    if (_isShow == YES && _isPingJia == YES) {
        return 2;
    }
    return 1;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 1 && _isPingJia == NO) {
        
        EvaluationCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EvaluationCell"];
        cell.scoreLabel.text = [NSString stringWithFormat:@"评价可获得%@积分",_integral];
        
        return cell;
        
    }else if (indexPath.row == 1 && _isPingJia ==YES){
        
        EvaluationedCell *cell = [tableView dequeueReusableCellWithIdentifier:@"EvaluationedCell"];
        
        return cell;
    }
    else{
        
        OrderStatusCell *cell = [tableView dequeueReusableCellWithIdentifier:@"OrderStatusCell"];
        
        cell.orderStatus.text = [NSString stringWithFormat:@"订单状态:%@",[_statusArr lastObject]];
        
        cell.orderId = _orderId;
        
        cell.orderNum.text = [NSString stringWithFormat:@"订单号:%@",_orderId];
        
        cell.orderAddress.text = [NSString stringWithFormat:@"订单地址:%@",_address];
        cell.scoreLabel.hidden = YES;
//        if ([[_statusArr lastObject] isEqualToString:@"付款"]) {
//            cell.scoreLabel.hidden = NO;
//            cell.scoreLabel.text = [NSString stringWithFormat:@"评价可获得%@积分",_integral];
//        }
        //日期时间转换
        
        NSMutableArray *array = [NSMutableArray array];
        for (NSString *tmpString in _timeArr) {
            
            NSString *month = [tmpString substringWithRange:NSMakeRange(5, 2)];
            
            NSString *day = [tmpString substringWithRange:NSMakeRange(8, 2)];
            
            NSString *hour = [tmpString substringWithRange:NSMakeRange(11, 2)];
            
            NSString *minute = [tmpString substringWithRange:NSMakeRange(14, 2)];
            
            NSString *timeString = [NSString stringWithFormat:@"%@.%@ %@:%@",month,day,hour,minute];
            
            [array addObject:timeString];
            
        }
        
        if (array.count == _statusArr.count) { 
            
            [cell setupCellWithData:array statusText:_statusArr purId:_purId];
        }else{
            
        }
        
        return cell;
    }
    return nil;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (indexPath.row == 1) {
        if (iphone5x_4_0) {
            return 100;
        }else if (kDevice_Is_iPhoneX){
            return 135;
        }
        return 135;
    }
    if (_isShow == YES) {
        if (iphone5x_4_0) {
            return kScreenHeight - 164;
        }else if (kDevice_Is_iPhoneX){
            return kScreenHeight -200;
        }
        return kScreenHeight - 200;
    }
    return kScreenHeight - 64;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    if (indexPath.row == 1) {
        NSLog(@"点击评价");
        if (_isShow == YES && _isPingJia == NO) {
            
            [self loadClicked];
        }
        if (_isShow == YES && _isPingJia == YES) {
            
            [self requestData];
        }
    }
}

-(void)loadClicked
{
    _sheetView = [[SheetView alloc]init];
    _sheetView.orderId = _orderId;
    [_sheetView showInView:[self getCurrentVC].view];
    
}
//获取当前屏幕显示的viewcontroller
- (UIViewController *)getCurrentVC
{
    UIViewController *result = nil;
    
    UIWindow * window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal)
    {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for(UIWindow * tmpWin in windows)
        {
            if (tmpWin.windowLevel == UIWindowLevelNormal)
            {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    
    if ([nextResponder isKindOfClass:[UIViewController class]])
        result = nextResponder;
    else
        result = window.rootViewController;
    
    return result;
}

- (void)requestData{
    
    NSString *url = [QParamService urlWithAction:@"selUserEvaluatetanker"];
    NSDictionary *para= [QParamService GainValuationDataWithOrderId:_orderId];
    
    [[QHttpManager sharedManager] POST:url parameterMD5:para completion:^(NSData *data, NSDictionary *dict, NSError *error) {
        
        if(error){
            if([QUserInfo sharedInfo].isHaveNetWork == NO){
                
            }
            return ;
        }
        QBaseModel *basModel = [QBaseModel objectFromDict:dict];
        if([basModel.result isEqualToString:@"success"]){
            
            NSDictionary *dic =  basModel.items;
            if ([dic.allKeys containsObject:@"evalJsonstr"]) {
                NSString *evalJsonstr = [dic objectForKey:@"evalJsonstr"];
                
                NSString *string = [evalJsonstr stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"\""]];
                if (string == nil) {
                    
                }
                
                NSData *jsonData = [string dataUsingEncoding:NSUTF8StringEncoding];
                NSError *err;
                _evalArr = [NSMutableArray new];
                _evalArr = [NSJSONSerialization JSONObjectWithData:jsonData
                                                           options:NSJSONReadingMutableContainers
                                                             error:&err];
                
                if (_evalArr.count>0) {
                    
                    NSString *content = [dic objectForKey:@"content"];
                    if (content != nil ||![content isEqualToString:@""]) {
                        NSDictionary *dic = @{@"content":content};
                        [_evalArr addObject:dic];
                    }
                    
                    [self showPopView];
    
                }
                if(err) {
                    NSLog(@"json解析失败：%@",err);
                }
            }
        }
    }];
}
- (void)showPopView
{
    SheetView1 *sheet = [[SheetView1 alloc]init];
    sheet.dataSource = _evalArr;
    UIViewController *vc = [self getCurrentVC];
    [sheet showInView:vc.view];
    
}
@end
